import { Repository , getRepository , FindManyOptions } from 'typeorm';
import { validate, ValidationError } from "class-validator";
import { TeamRankData } from '../entity/team_rank_data';
import { BaseContext } from 'koa';

export default class TeamRankDataControl {
    public static async saveTeamRankData(teamRankData: Array<TeamRankData>) {
        const teamRankDataRepository: Repository<TeamRankData> = getRepository(TeamRankData);
        const errors: ValidationError[] = await validate(teamRankData);
        try {
            if(errors.length > 0) console.log(errors);
            else await teamRankDataRepository.save(teamRankData);
        } catch (error) {
            console.log(error);
        }
    }

    public static async getTeamRankDatas(ctx: BaseContext) {
        try {
            const TeamRankDataRepository: Repository<TeamRankData> = getRepository(TeamRankData);
            let { pageSize , pageIndex , teamId , season , seasonType } = ctx.request.body;
            pageIndex = pageIndex && pageIndex > 0 ? pageIndex-1 : 0;
            pageSize = pageSize || 30;
            let queryOptions: FindManyOptions<TeamRankData> = {
                relations: ["teams","season","seasonType"],
                order: {
                    winPct: "DESC"
                },
                where: {},
                skip: pageIndex*pageSize,
                take: pageSize,
            }
            let where = {};
            if(teamId && teamId !== '') Object.assign({},where,{ "teams.id": teamId  })
            if(season && season !== '') Object.assign({},where,{ "season.name": season })
            if(seasonType && seasonType !== '') Object.assign({},where,{ "seasonType.name": seasonType })
            queryOptions.where = where;
            const [ teamRankDataLists , total ] = await TeamRankDataRepository.findAndCount(queryOptions);
            ctx.status = 200;
            ctx.body = ctx.util.response(ctx.ERROR.ERRORCODE_SUCCESS,ctx.ERROR.ERRORMSG_SUCCESS,{
                teamRankDataLists,
                total
            });
        } catch (error) {
            ctx.status = 500;
            ctx.app.emit('error', {
                code: ctx.ERROR.ERRORCODE_SYSTEMERROR,
                message: ctx.ERROR.ERRORMSG_SYSTEMERROR
            }, ctx);
        }
    }
}